package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {

        //根据username查询到user
        User user = userDao.findByUsername(username);
        if (user != null) {
            //根据userId查询到角色集合
            Set<Role> roleSet = roleDao.findByUserId(user.getId());
            System.out.println("roleSet = ====================================" + roleSet);
            if (roleSet != null && roleSet.size() > 0) {
                //遍历集合 查询到每一个角色对应的权限
                for (Role role : roleSet) {
                    System.out.println(role.getId() + "=======================================================");
                    Set<Permission> permissionSet = permissionDao.findByRoleId(role.getId());
                    if (permissionSet != null && permissionSet.size() >0){

                        //添加权限到role中
                        role.setPermissions(permissionSet);
                    }
                }
                //添加角色到user中
                user.setRoles(roleSet);
            }
        }
        return user;
    }


}
